<?php
if(!function_exists('success')){
    function success($data=[],$msg="",$code=1){
        return [
            'code'=>$code,
            'msg'=>$msg,
            'data'=>$data,
        ];
    }
}
if(!function_exists('error')){
    function error($msg='操作失败',$data=[],$code=-1){
        return [
            'code'=>$code,
            'msg'=>$msg,
            'data'=>$data
        ];
    }
}
if(!function_exists('uuid')){
    /**
     * uuid生成36个字符
     * @param string $prefix 前缀
     * @return string
     */
    function uuid($prefix = '')
    {
        $len = strlen($prefix);
        if($len>=12){
            return false;
        }
        $chars = md5(uniqid(mt_rand(), true));
        $uuid = substr($chars, 0, 8) . '-';
        $uuid .= substr($chars, 8, 4) . '-';
        $uuid .= substr($chars, 12, 4) . '-';
        $uuid .= substr($chars, 16, 4) . '-';
        $uuid .= substr($chars, 20, 12-$len);
        return $prefix . $uuid;
    }
}
if(!function_exists('getTree')){
    /**
     * @param $arr
     * @param $parent_id
     * @param string $field
     * @param string $key
     * @param string $pk
     * @return array
     */
    function getTree($arr, $parent_id=0, $field="parent_id", $key="children", $pk="id"){
        $tree = [];
        foreach ($arr as $k=>$v){
            if ($v[$field] == $parent_id){
                $v[$key] = getTree($arr,$v[$pk],$field,$key,$pk);
                if ($v[$key] == null){
                    unset($v[$key]);
                }
                $tree[] = $v;
            }
        }
        return $tree;
    }
}
if(!function_exists('upToLower')){
    /**
     * 大写字母转小写加连字符{}包裹的地方不转
     * @param string $str
     * @param string $replacement
     * @return string
     */
    function upToLower(string $str,$replacement="-"){
        $newStr = "";
        $len = strlen($str);
        $skip = false;
        for($i = 0;$i<$len;$i++){
            $item = $str[$i];
            if($item=="{"){
                $newStr .= $item;
                $skip = true;
                continue;
            }
            if($item=="}"){
                $newStr .= $item;
                $skip = false;
                continue;
            }
            if($i > 0&&$skip == false){
                if(ord($item)>=60&&ord($item)<=90){
                    $item = $replacement.chr(ord($item)+32);
                }
            }
            $newStr .= $item;
        }
        return $newStr;
    }
}
